import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/app_state.dart';
import '../models/question.dart';
import '../services/api_service.dart';
import '../widgets/theme_selector.dart';

class QuestionnairePage extends StatefulWidget {
  const QuestionnairePage({super.key});

  @override
  State<QuestionnairePage> createState() => _QuestionnairePageState();
}

class _QuestionnairePageState extends State<QuestionnairePage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _slideAnimation;
  late Animation<double> _fadeAnimation;

  late List<SCLQuestion> _questions;

  @override
  void initState() {
    super.initState();
    _questions = QuestionnaireData.getSCLQuestions();

    _animationController = AnimationController(
      duration: const Duration(milliseconds: 400),
      vsync: this,
    );

    _slideAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );

    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.background,
      body: SafeArea(
        child: Consumer<AppState>(
          builder: (context, appState, child) {
            return Column(
              children: [
                // 顶部工具栏
                _buildTopBar(appState),

                // 进度指示器
                _buildProgressIndicator(appState),

                // 问卷内容
                Expanded(child: _buildQuestionnaireContent(appState)),

                // 底部按钮
                _buildBottomButtons(appState),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildTopBar(AppState appState) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              IconButton(
                onPressed: () {
                  if (appState.currentSCLQuestionIndex > 0) {
                    appState.setCurrentSCLQuestionIndex(
                      appState.currentSCLQuestionIndex - 1,
                    );
                    _animateTransition();
                  } else {
                    appState.setCurrentPage(1); // 返回基本信息页面
                  }
                },
                icon: const Icon(Icons.arrow_back_ios),
              ),
              const SizedBox(width: 8),
              Text(
                'SCL-90 问卷',
                style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const ThemeSelector(),
        ],
      ),
    );
  }

  Widget _buildProgressIndicator(AppState appState) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '第${appState.currentSCLQuestionIndex + 1}题 / 90题',
                style: Theme.of(context).textTheme.bodyMedium,
              ),
              Text(
                '${((appState.currentSCLQuestionIndex + 1) / 90 * 100).toInt()}%',
                style: Theme.of(context).textTheme.bodyMedium,
              ),
            ],
          ),
          const SizedBox(height: 8),
          LinearProgressIndicator(
            value: (appState.currentSCLQuestionIndex + 1) / 90,
            backgroundColor: Colors.grey.shade300,
            valueColor: AlwaysStoppedAnimation<Color>(
              Theme.of(context).primaryColor,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildQuestionnaireContent(AppState appState) {
    if (appState.currentSCLQuestionIndex >= _questions.length) {
      return const Center(child: Text('问卷已完成'));
    }

    final currentQuestion = _questions[appState.currentSCLQuestionIndex];
    final currentAnswer = appState.getSCLAnswer(currentQuestion.id);

    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        return Transform.translate(
          offset: Offset(_slideAnimation.value * 100, 0),
          child: Opacity(
            opacity: _fadeAnimation.value,
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 问题卡片
                  _buildQuestionCard(currentQuestion, currentAnswer),

                  const SizedBox(height: 32),

                  // 答案选项
                  _buildAnswerOptions(currentQuestion, currentAnswer, appState),

                  const SizedBox(height: 32),

                  // 分类标签
                  _buildCategoryTag(currentQuestion),

                  const SizedBox(height: 100), // 底部按钮空间
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildQuestionCard(SCLQuestion question, int? currentAnswer) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 0,
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Center(
                  child: Text(
                    '${question.id}',
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Text(
                    //   '问题 ${question.id}',
                    //   style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    //     color: Colors.grey.shade600,
                    //   ),
                    // ),
                    // const SizedBox(height: 4),
                    Text(
                      '最近一周，您有没有下列感受？',
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Colors.grey.shade500,
                        fontSize: 16, // 调整文字大小
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          Text(
            question.text,
            style: Theme.of(context).textTheme.headlineMedium?.copyWith(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              height: 1.4,
            ),
          ),
          if (currentAnswer != null) ...[
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: Theme.of(context).primaryColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.check_circle,
                    color: Theme.of(context).primaryColor,
                    size: 16,
                  ),
                  const SizedBox(width: 4),
                  Text(
                    '已选择：${QuestionnaireData.scaleOptions[currentAnswer - 1]}',
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildAnswerOptions(
    SCLQuestion question,
    int? currentAnswer,
    AppState appState,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '请选择符合您情况的选项：',
          style: Theme.of(
            context,
          ).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 16),
        ...QuestionnaireData.scaleOptions.asMap().entries.map((entry) {
          int index = entry.key;
          String option = entry.value;
          int score = index + 1;
          bool isSelected = currentAnswer == score;

          return GestureDetector(
            onTap: () {
              appState.saveSCLAnswer(question.id, score);
              _animateTransition();

              // 自动跳转到下一题
              Future.delayed(const Duration(milliseconds: 300), () {
                if (appState.currentSCLQuestionIndex < 89) {
                  appState.setCurrentSCLQuestionIndex(
                    appState.currentSCLQuestionIndex + 1,
                  );
                }
              });
            },
            child: Container(
              width: double.infinity,
              margin: const EdgeInsets.only(bottom: 12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: isSelected
                    ? Theme.of(context).primaryColor.withOpacity(0.1)
                    : Colors.grey.shade50,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: isSelected
                      ? Theme.of(context).primaryColor
                      : Colors.grey.shade300,
                  width: isSelected ? 2 : 1,
                ),
              ),
              child: Row(
                children: [
                  Container(
                    width: 24,
                    height: 24,
                    decoration: BoxDecoration(
                      color: isSelected
                          ? Theme.of(context).primaryColor
                          : Colors.transparent,
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: isSelected
                            ? Theme.of(context).primaryColor
                            : Colors.grey.shade400,
                        width: 2,
                      ),
                    ),
                    child: Center(
                      child: Text(
                        score.toString(),
                        style: TextStyle(
                          color: isSelected
                              ? Colors.white
                              : Colors.grey.shade600,
                          fontWeight: FontWeight.bold,
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      option,
                      style: TextStyle(
                        color: isSelected
                            ? Theme.of(context).primaryColor
                            : Colors.grey.shade700,
                        fontWeight: isSelected
                            ? FontWeight.w600
                            : FontWeight.normal,
                        fontSize: 16,
                      ),
                    ),
                  ),
                  if (isSelected)
                    Icon(
                      Icons.check_circle,
                      color: Theme.of(context).primaryColor,
                      size: 20,
                    ),
                ],
              ),
            ),
          );
        }).toList(),
      ],
    );
  }

  Widget _buildCategoryTag(SCLQuestion question) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.category, color: Colors.grey.shade600, size: 16),
          const SizedBox(width: 4),
          Text(
            '分类：${question.category}',
            style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomButtons(AppState appState) {
    bool canGoNext = appState.currentSCLQuestionIndex < 89;
    bool canGoBack = appState.currentSCLQuestionIndex > 0;
    bool isLastQuestion = appState.currentSCLQuestionIndex == 89;
    bool hasAnswered =
        appState.getSCLAnswer(
          _questions[appState.currentSCLQuestionIndex].id,
        ) !=
        null;

    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          if (canGoBack)
            Expanded(
              child: OutlinedButton(
                onPressed: () {
                  appState.setCurrentSCLQuestionIndex(
                    appState.currentSCLQuestionIndex - 1,
                  );
                  _animateTransition();
                },
                style: OutlinedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  side: BorderSide(color: Theme.of(context).primaryColor),
                ),
                child: const Text('上一题'),
              ),
            ),

          // 间距
          if (canGoBack && (canGoNext || isLastQuestion))
            const SizedBox(width: 12),

          // 下一题按钮（只在非最后一题时显示）
          if (canGoNext && !isLastQuestion)
            Expanded(
              flex: canGoBack ? 1 : 2,
              child: ElevatedButton(
                onPressed: hasAnswered
                    ? () {
                        appState.setCurrentSCLQuestionIndex(
                          appState.currentSCLQuestionIndex + 1,
                        );
                        _animateTransition();
                      }
                    : null,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
                child: const Text('下一题'),
              ),
            ),

          // 完成测试按钮（只在最后一题且已回答时显示）
          if (isLastQuestion)
            Expanded(
              flex: canGoBack ? 1 : 2,
              child: ElevatedButton(
                onPressed: hasAnswered
                    ? () async {
                        await _submitQuestionnaire(appState);
                      }
                    : null,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  backgroundColor: Colors.green,
                ),
                child: appState.isLoading
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(
                            Colors.white,
                          ),
                        ),
                      )
                    : const Text(
                        '完成测试',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
              ),
            ),
        ],
      ),
    );
  }

  void _animateTransition() {
    _animationController.reset();
    _animationController.forward();
  }

  Future<void> _submitQuestionnaire(AppState appState) async {
    // 调试信息
    print('=== 提交问卷调试信息 ===');
    print('当前问题索引: ${appState.currentSCLQuestionIndex}');
    print('已回答问题数量: ${appState.sclAnswers.length}');
    print('是否所有问题已回答: ${appState.isAllSCLQuestionsAnswered()}');
    print('基本信息: ${appState.basicInfo}');

    appState.setLoading(true);

    try {
      final apiService = ApiService();
      final submissionData = appState.getSubmissionData();

      print('准备提交的数据: $submissionData');

      final result = await apiService.submitAssessment(
        basicInfo: submissionData['basic_info']!,
        sclAnswers: Map<String, int>.from(submissionData['scl_answers']!),
      );

      print('API返回结果: $result');

      if (result['success'] == true) {
        // 保存测试ID
        appState.setTestId(result['test_id']);
        // 保存分析结果
        appState.setAnalysisResult(result['analysis']);
        appState.setCurrentPage(3); // 跳转到结果页面
      } else {
        throw Exception('提交失败：服务器返回错误');
      }
    } catch (e) {
      print('提交失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('提交失败：$e'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    } finally {
      appState.setLoading(false);
    }
  }
}
